package com.xingchen.netty.global;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ChannelSupervise {
    private   static ChannelGroup GlobalGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private  static ConcurrentMap<String, ChannelId> ChannelMap=new ConcurrentHashMap();
    public  static boolean addChannel(Channel channel){

        GlobalGroup.add(channel);
        String  cid =channel.id().asShortText();
        ChannelMap.put(cid,channel.id());
        return true;
    }
    public static boolean removeChannel(Channel channel){
        GlobalGroup.remove(channel);
        String  cid =channel.id().asShortText();
        ChannelMap.remove(cid);
        return true;
    }
    public static  Channel findChannel(String id){
        ChannelId cid=ChannelMap.get(id);
        if(cid!=null){
            return GlobalGroup.find(cid);
        }
        return null;
    }
    public static boolean send2All(TextWebSocketFrame tws){
        GlobalGroup.writeAndFlush(tws);
        return true;
    }
    public  static  boolean send(String cid,TextWebSocketFrame tws){
        Channel channel= findChannel(cid);
        if(channel!=null){
            channel.writeAndFlush(tws);
            return true;
        }
        return false;
    }
}
